package com.qf.service.impl;

import com.qf.cache.RoleCache;
import com.qf.entity.SysRole;
import com.qf.exceptions.AddDataException;
import com.qf.exceptions.ResultCode;
import com.qf.exceptions.UpdateException;
import com.qf.mapper.SysRoleDao;
import com.qf.mapper.SysRoleMapper;
import com.qf.pojo.CheckType;
import com.qf.service.RoleService;
import com.qf.utils.SecurityUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;

/**
 * @Author ztf
 * @Date 16:30 2022/1/10
 **/
@Service
@Transactional(rollbackFor = RuntimeException.class)
public class RoleServiceImpl implements RoleService {
    private SysRoleMapper sysRoleMapper;
    private SysRoleDao sysRoleDao;
    private RoleCache roleCache;

    public void setSysRoleMapper(SysRoleMapper sysRoleMapper) {
        this.sysRoleMapper = sysRoleMapper;
    }

    public void setSysRoleDao(SysRoleDao sysRoleDao) {
        this.sysRoleDao = sysRoleDao;
    }

    public void setRoleCache(RoleCache roleCache) {
        this.roleCache = roleCache;
    }

    @Override
    public void addRole(SysRole role) {
        Assert.isTrue(role.isEmpty(CheckType.ADD), () -> {
            throw new AddDataException("添加角色失败，数据不完整", ResultCode.DATA_NULL);
        });
        role.setCreateBy(SecurityUtils.getUser().getUsername());
        role.setCreateTime(new Date());
        sysRoleDao.insert(role);
    }

    @Override
    public List<SysRole> findAllRoles() {
        List<SysRole> allData = roleCache.getAllData();
        return allData;
    }

    @Override
    public SysRole findRolesById(Long id) {
        SysRole roleCacheValue = roleCache.getValue(id);
        return roleCacheValue;
    }

    @Override
    public void updateRole(SysRole role) {
        Assert.isTrue(role.isEmpty(CheckType.UPDATE), () -> {
            throw new UpdateException("修改角色信息失败，参数不完整", ResultCode.DATA_NULL);
        });
        role.setUpdateBy(SecurityUtils.getUser().getUsername());
        role.setUpdateTime(new Date());
        sysRoleDao.updateByPrimaryKey(role);
    }

    @Override
    public void deleteByIds(List<Integer> roleIds) {
        sysRoleMapper.deleteByIds(roleIds);
    }

}
